<script setup lang="ts">
import { dictionaryCreateApi, dictionaryUpdateApi } from "@/api/system/dict";
import { ElMessage } from 'element-plus'
import { useRequest } from "vue-hooks-plus";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  dictionaryRemark: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['cancel'])

const formRef = ref()
const form = ref({
  name: '',
  dictionaryRemark: ''
})

const rules = ref({
  name: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
})

const { run: add, loading: addLoading } = useRequest(dictionaryCreateApi, {
  manual: true,
  onSuccess: () => {
    ElMessage({
      message: '新增成功',
      type: 'success',
    })
    emits('cancel', true)
  }
})

const { run: update, loading: updateLoading } = useRequest(dictionaryUpdateApi, {
  manual: true,
  onSuccess: () => {
    ElMessage({
      message: '编辑成功',
      type: 'success',
    })
    emits('cancel', true)
  }
})

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (props.id) {
        update({
          id: props.id,
          ...form.value
        })
      } else {
        add(form.value)
      }
    }
  })
}

watch(() => props.visible, () => {
  if (props.visible) {
    form.value = {
      name: props.name,
      dictionaryRemark: props.dictionaryRemark
    }
  }
}, { immediate: true })
</script>

<template>
  <!-- 添加或修改参数配置对话框 -->
  <el-dialog v-model="props.visible" :title="props.title" width="600px" align-center @close="emits('cancel')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入字典名称" clearable :maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="备注" prop="dictionaryRemark">
        <el-input v-model="form.dictionaryRemark" type="textarea" placeholder="请输入内容" clearable :maxlength="200"
          show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emits('cancel', false)">取消</el-button>
        <el-button type="primary" :loading="addLoading || updateLoading" @click="handleSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-textarea__inner) {
  min-height: 136px !important;
}
</style>